<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>

if (document.location.host != "subdomain.example.test:8443") {
  document.location = "https://subdomain.example.test:8443/credentialmanager/publickeycredential-same-origin-with-ancestors.html";
  promise_test(_ => new Promise(_ => {}), "Stall tests on the wrong host.");
}

const SAME_ORIGIN = "https://subdomain.example.test:8443";
const CROSS_ORIGIN = "https://notexample.test:8443";

const VALID_IFRAME_CASES = [
    { 'outerOrigin': SAME_ORIGIN,
      'innerOrigin': ''},
    { 'outerOrigin': SAME_ORIGIN,
      'innerOrigin': SAME_ORIGIN}
];

const INVALID_IFRAME_CASES = [
    { 'outerOrigin': CROSS_ORIGIN,
      'innerOrigin': ''},
    { 'outerOrigin': SAME_ORIGIN,
      'innerOrigin': CROSS_ORIGIN},
    { 'outerOrigin': CROSS_ORIGIN,
      'innerOrigin': SAME_ORIGIN},
    { 'outerOrigin': CROSS_ORIGIN,
      'innerOrigin': CROSS_ORIGIN},
];

const HELPER_FILES = [
    'publickey-create-helper.html', 'publickey-get-helper.html'
];

function createNestedIframeTest(outerOrigin, innerOrigin, expectation, helperfile) {
    return function (t) {
        window.addEventListener("load", _ => {
            var iframe = document.createElement("iframe");
            if (innerOrigin) {
                // Nested iframe
                iframe.src = outerOrigin + "/credentialmanager/resources/echoing-nester.html?origin="
                    + innerOrigin + "&file=" + helperfile;
            } else {
                iframe.src = outerOrigin + "/credentialmanager/resources/" + helperfile;
            }
            window.addEventListener("message", t.step_func(e => {
                if (e.source == iframe.contentWindow) {
                    assert_equals(e.data, expectation);
                    t.done();
                }
            }));
            document.body.appendChild(iframe);
        });
    };
}

for (let test of VALID_IFRAME_CASES) {
    for (let file of HELPER_FILES) {
        async_test(createNestedIframeTest(test.outerOrigin, test.innerOrigin, "SUCCESS", file),
        file + " with inner origin: " + test.innerOrigin + ", outer origin: " + test.outerOrigin + "succeeds");
    }
}

for (let test of INVALID_IFRAME_CASES) {
    for (let file of HELPER_FILES) {
        async_test(createNestedIframeTest(test.outerOrigin, test.innerOrigin, "NotAllowedError",file),
        file + " with inner origin: " + test.innerOrigin + ", outer origin: " + test.outerOrigin + "fails");
    }
}

</script>
